package com.biu.billiards.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

public class TokenUtils {

    //token到期时间3天
    private static final long EXPIRE_TIME= 72*60*60*1000;
    //密钥盐
    private static final String TOKEN_SECRET="ljdyaisdsfahijin**3nkjnj??";


    /**
     * 生成token
     * @param
     * @return
     */
    public static String sign(String account){

        String token=null;
        try {
            Date expireAt=new Date(System.currentTimeMillis()+EXPIRE_TIME);
            token = JWT.create()
                    //发行人
                    .withIssuer("biu")
                    //存放数据
                    .withClaim("userAccount",account)
                    //过期时间
                    .withExpiresAt(expireAt)
                    .sign(Algorithm.HMAC256(TOKEN_SECRET));


        } catch (IllegalArgumentException | JWTCreationException je) {

        }
        return token;
    }


    /**
     * token验证
     * @param token
     * @return
     */
    public static Boolean verify(String token){

        try {
            //创建token验证器
            JWTVerifier jwtVerifier=JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("biu").build();
            DecodedJWT decodedJWT=jwtVerifier.verify(token);
            System.out.println("认证通过：");
            System.out.println("userAccount: " + decodedJWT.getClaim("userAccount").asString());
            System.out.println("过期时间：      " + decodedJWT.getExpiresAt());
        } catch (IllegalArgumentException | JWTVerificationException e) {
            //抛出错误即为验证不通过
            return false;
        }
        return true;
    }

    public static String getAccount(String token){

        JWTVerifier jwtVerifier=JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("biu").build();
        String userAccount = "";

        try {


            DecodedJWT decodedJWT=jwtVerifier.verify(token);
            userAccount=decodedJWT.getClaim("userAccount").asString();

            System.out.println("账号是");
            System.out.println(userAccount);
        }catch (IllegalArgumentException | JWTVerificationException e) {
            //抛出错误即为验证不通过
            System.out.println("不通过");
        }

        return userAccount;
    }







}
